// auth.interceptor.ts
import { CallHandler, ExecutionContext, HttpException, HttpStatus, Inject, Injectable, Logger, NestInterceptor } from '@nestjs/common'
import { JwtService } from '@nestjs/jwt'
import { Observable } from 'rxjs'
import { RedisService } from 'src/redis/redis.service'

@Injectable()
export class AuthInterceptor implements NestInterceptor {
  private readonly logger = new Logger(AuthInterceptor.name)

  @Inject(JwtService)
  private jwtService: JwtService

  @Inject(RedisService)
  private redisService: RedisService

  async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
    const request = context.switchToHttp().getRequest()
    const token = request.headers.authorization?.split(' ')[1]

    if (!token) {
      return Promise.resolve(next.handle())
    }

    try {
      const payload = this.jwtService.verify(token)
      const loginToken = await this.redisService.get(`valid_user_token_${payload.userId}`)
      this.logger.debug('🚀 ~ jwt use token:', token)
      this.logger.debug('🚀 ~ redis login Token:', loginToken)
      if (loginToken !== token) {
        throw new HttpException('当前账号身份信息不可用，请稍后重新登录', HttpStatus.UNAUTHORIZED)
      }
    }
    catch (e) {
      throw new HttpException(e.message, HttpStatus.UNAUTHORIZED)
    }
    return next.handle()
  }
}
